﻿using Microsoft.AspNetCore.Mvc.RazorPages;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace DotNetStar.TheKing.Web.Pages.Account
{
    using DotNetStar.TheKing.Infrastructure;
    using Microsoft.AspNetCore.Mvc;
    using Services;
    public class LoginModel:PageModel
    {
        private readonly UserService _userService;
        private readonly VerifyCodeService _verifyCodeService;


        public LoginModel(UserService userService,
            VerifyCodeService verifyCodeService)
        {
            _userService = userService;
            this._verifyCodeService = verifyCodeService;
        }

        public string ReturnUrl => Request.Query["returnUrl"].ToString().IsNullOrEmpty() ? Url.Page("/Index") : Request.Query["returnUrl"].ToString();

        public IActionResult OnGet()
        {
            if (User.Identity.IsAuthenticated)
            {
                return Redirect(this.ReturnUrl);
            }
            return Page();
        }

        public async Task<IActionResult> OnPostMobileCodeAsync(string mobile, string code)
        {
            if (mobile.IsNullOrWhiteSpace())
            {
                return StatusCode(400, "手机号不能为空");
            }

            if (code.IsNullOrWhiteSpace())
            {
                return StatusCode(400, "验证码不能为空");
            }

            var validateResult = _verifyCodeService.VerifyCode(mobile, code);
            if (!validateResult)
            {
                return StatusCode(400, "验证码不正确");
            }

            var user = await _userService.GetUserAsync(mobile, AccountTypes.Mobile);

            if (user == null)
            {
                return StatusCode(400, "手机号码不存在");
            }
            
            //认证
            await HttpContext.SignInAsync(user);

            return StatusCode(200);
        }

        public async Task<IActionResult> OnPostAccountPasswordAsync(string account,string password)
        {
            try
            {
                var user = await _userService.GetUserAsync(account, password);

                if (user == null)
                {
                    return StatusCode(400, "帐号或密码不正确");
                }
                
                //认证
                await HttpContext.SignInAsync(user);

                return StatusCode(200);
            }
            catch (Exception ex)
            {
                return StatusCode(400, ex.Message);
            }
        }
    }
}
